﻿using System;
using System.Data.Services.Client;
using Azure.Toolkit.Azure;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.StorageClient;
using SimplePoll.Web.DataAccess;
using SimplePoll.Web.Models;

namespace SimplePoll.Web
{
    public class WebRole : AzureRoleEntryPoint
    {
        protected override void Configure(DiagnosticMonitorConfiguration config)
        {
            base.Configure(config);
            //Performance Counter for cpu usage
            var cpuUsage = new PerformanceCounterConfiguration
                               {
                                   CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                                   SampleRate = TimeSpan.FromSeconds(5)
                               };

            //Performance Counter Subscription for Memory
            var pccMemory = new PerformanceCounterConfiguration
                                {
                                    CounterSpecifier = @"\Memory\Available Mbytes",
                                    SampleRate = TimeSpan.FromSeconds(5)
                                };

            // ASP.NET Applications(__Total__)\Requests/Sec
            var requestsPerSec = new PerformanceCounterConfiguration
                                     {
                                         CounterSpecifier = @"\ASP.NET Applications(__Total__)\Requests/Sec",
                                         SampleRate = TimeSpan.FromSeconds(5)
                                     };

            config.PerformanceCounters.DataSources.Add(cpuUsage);
            config.PerformanceCounters.DataSources.Add(pccMemory);
            config.PerformanceCounters.DataSources.Add(requestsPerSec);
        }

        public override bool OnStart()
        {
            bool startUp = base.OnStart();
            CloudStorageAccount account = CloudConfiguration.GetStorageAccount("DataConnectionString");

            // Tables
            var cloudTableClient = new CloudTableClient(account.TableEndpoint.ToString(), account.Credentials);
            cloudTableClient.CreateTableIfNotExist<Poll>(PollDataContext.PollTable);
            cloudTableClient.CreateTableIfNotExist<PollAnswer>(PollDataContext.PollAnswerTable);
            cloudTableClient.CreateTableIfNotExist<PollResultRow>(PollDataContext.PollResultTable);
            return startUp;
        }
    }
}